﻿// 2025/10/14: 首个版本

using System;
using System.Xml;
using Avalonia.Media;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using ASEva;
using ASEva.UIAvalonia;
using ASEva.Utility;

namespace CommonSource
{
    partial class LicenseChooser : DialogPanel
    {
        public LicenseChooser() // For designer
        {
            InitializeComponent();
            language = new LanguageSwitch(Resources, AgencyLocal.GetAppLanguage());
        }

        public LicenseChooser(String description, String rawMachineCode, bool chinese = false, String title = null, String iconResourceName = null)
        {
            InitializeComponent();
            SetFixMode(540, 145, true);
            language = new LanguageSwitch(Resources, chinese ? Language.Chinese : Language.English);
            Title = String.IsNullOrEmpty(title) ? language["title"] : title;
            Icon = ResourceLoader.Load(iconResourceName)?.ToAvaloniaWindowIcon();

            String machineCode = null;
            if (rawMachineCode != null)
            {
                var cleanMachineCode = rawMachineCode.Replace('0', 'K').Replace('1', 'M').Replace('8', 'H').Replace('B', 'J').Replace('D', 'P'); // KM234567H9AJCPEF
                machineCode = cleanMachineCode.Substring(0, 2) + "-" +
                    cleanMachineCode.Substring(2, 2) + "-" +
                    cleanMachineCode.Substring(4, 2) + "-" +
                    cleanMachineCode.Substring(6, 2) + "-" +
                    cleanMachineCode.Substring(8, 2) + "-" +
                    cleanMachineCode.Substring(10, 2);
            }

            labelDescription.Content = description;
            if (machineCode != null)
            {
                stackPanelMachineCode.IsVisible = buttonCopyClipboard.IsVisible = true;
                labelMachineCode.Content = machineCode;
            }

            buttonConfirm.Click += delegate
            {
                BoolResult = true;
                Close();
            };

            buttonQuit.Click += delegate
            {
                Close();
            };

            buttonFromFile.Click += async delegate
            {
                var selected = await this.GetStorageProvider().OpenFilePickerAsync(new FilePickerOpenOptions()
                {
                    Title = language["dialog-title"],
                    SuggestedStartLocation = await this.GetStorageProvider().TryGetWellKnownFolderAsync(WellKnownFolder.Desktop),
                    FileTypeFilter =
                    [
                        new FilePickerFileType(language["suffix"]){ Patterns = ["*.aslic"] },
                    ]
                });
                if (selected == null || selected.Count == 0) return;

                var doc = new XmlDocument();
                try
                {
                    doc.Load(selected[0].Path.LocalPath);

                    String licenseStr = doc.DocumentElement.Attributes["license"].Value;
                    Convert.FromBase64String(licenseStr);
                    LicenseCode = licenseStr;

                    PluginCode = doc.DocumentElement.Attributes["plugin_code"].Value;
                    
                    textLicenseCode.Text = licenseStr;
                }
                catch (Exception)
                {
                    await AgencyLocal.PopupError(language["invalid-file"]);
                    return;
                }
            };

            buttonCopyClipboard.Click += async delegate
            {
                await TopLevel.GetTopLevel(this).Clipboard.SetTextAsync(machineCode);
            };

            textLicenseCode.TextChanged += delegate
            {
                bool textOK = true;
                if (textLicenseCode.Text.Length == 0) textOK = false;
                try { Convert.FromBase64String(textLicenseCode.Text); }
                catch (Exception) { textOK = false; }
                buttonConfirm.IsEnabled = textOK;
                textLicenseCode.Foreground = textOK ? Brushes.Green : Brushes.Red;
            };
        }

        public String LicenseCode { get; set; }

        public String PluginCode { get; set; }

        private LanguageSwitch language;
    }
}